<!-- 生产数据趋势图 -->
<script lang="ts" setup>
import MyChart from '@/components/MyChart.vue'
import { ref, watch,computed } from 'vue'
const props = defineProps(['data'])
// 计算总百分比（始终为100%）
// 定义颜色配置
const defaultColors = ['#BFBFBF', '#F4EA2A', '#1AFA29', '#D81E06', '#E98F36']
// const twoItemColors = ['#D81E06', '#1AFA29']
const fourItemColors = ['#D81E06','#E98F36', '#F4EA2A', '#1AFA29']
watch(
  () => props.data,
  (val) => {
    console.log(val)
  }
)

const options = ref({
  color: defaultColors,
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    right: 0,
    top: 20,
    textStyle: {
      color: '#8FE1FF',
      fontSize: 18
    },
    // 格式化图例文本，显示名称、数值和百分比
    formatter: function(name: string) {
      // 从系列数据中找到对应项
      const seriesData = options.value.series[0].data as Array<{name: string, value: number}>
      const item = seriesData.find(item => item.name === name)

      if (!item) return name

      // 使用富文本格式拼接
      return `${name}: ${item.value}`
    },
    data: []
  },
  series: [
    {
      type: 'gauge',
      center: ['50%', '55%'],
      radius: '100%',
      startAngle: 210,
      endAngle: -30,
      axisLine: {
        lineStyle: {
          width: 20,
          color: [
            [0.6, '#D81E06'],
            [0.8, '#F4EA2A'],
            [1, '#1AFA29']
          ]
        }
      },
      pointer: {
        itemStyle: {
          color: 'auto'
        }
      },
      axisLabel: {
        color: 'inherit',
        distance: 20,
        fontSize: 12
      },
      detail: {
        valueAnimation: true,
        fontSize: 18,
        formatter: '达成率{value} %',
        color: 'inherit',
        offsetCenter: [0, '60%'],
      },
      data: [
        {
          value: 70
        }
      ]
    }

  ]
})

watch(
  () => props.data,
  (val) => {
    const { list } = val
    // 根据数据数量动态设置颜色
    options.value.color = list.length === 4 ? fourItemColors : defaultColors
    options.value.series[0].data = list
    options.value.legend.data = list.map((item: {name: string}) => item.name)
  },
  {
    deep: true, // 开启深度监听
    immediate: true // 立即触发一次（可选）
  }
)
</script>
<template>
  <MyChart height="200px" :option="options" />
</template>
